import { acceptHMRUpdate, defineStore } from 'pinia'
import { getCollectArticle } from '~/api/home'
import { onLogin } from '~/api/login'

export const useUserStore = defineStore('user', () => {
  const loginVisible = ref(false)
  function setLoginVisible(visible: boolean) {
    loginVisible.value = visible
  }
  const allowCloseLogin = ref(true)
  function setAllowCloseLogin(val: boolean) {
    allowCloseLogin.value = val
  }
  // const pathBeforeLogin = ref('')
  // function setPathBeforeLogin(path: string) {
  //   pathBeforeLogin.value = path
  // }
  const collectArticle = ref<any[]>([])
  const collectArticleMap = computed(() => {
    return collectArticle.value.reduce((acc, cur) => {
      acc[cur.target_id] = cur
      return acc
    }, {})
  })
  const userInfo = ref({})
  const expireTime = ref(0)
  const bxAuthTicket = ref('')
  const isLogin = computed(() => {
    return bxAuthTicket.value && userInfo.value?.user_no && true
  })

  if (import.meta.client) {
    const userInfoStr = localStorage.getItem('userInfo')
    if (userInfoStr) {
      userInfo.value = JSON.parse(userInfoStr)
      expireTime.value = Number(localStorage.getItem('expireTime'))
      bxAuthTicket.value = localStorage.getItem('bx_auth_ticket') || ''
    }
  }
  function setUserInfo(userInfoData: any) {
    userInfo.value = userInfoData
    if (import.meta.client) {
      localStorage.setItem('userInfo', JSON.stringify(userInfoData))
    }
  }
  async function accountLogin(formModel) {
    const res = await onLogin(formModel)
    if (res?.state === 'SUCCESS') {
      setLoginVisible(false)
      ElMessage.success('登录成功')
      navigateTo('/')
      const response = res.response[0].response
      if (response?.bx_auth_ticket) {
        bxAuthTicket.value = response.bx_auth_ticket
        setUserInfo(response.login_user_info)
        expireTime.value = response.expire_time
        if (import.meta.client) {
          localStorage.setItem('bx_auth_ticket', response.bx_auth_ticket)
          localStorage.setItem('expireTime', response.expire_time)
        }
        getCollectArticleList()
        // if (pathBeforeLogin.value) {
        //   const url = pathBeforeLogin.value
        //   pathBeforeLogin.value = ''
        //   navigateTo(url)
        // }
      }
    }
    else if (res?.resultMessage) {
      ElMessage.error(res.resultMessage)
    }
  }


  
  function getCollectArticleList() {
    getCollectArticle().then((res) => {
      if (res.state === 'SUCCESS') {
        collectArticle.value = res.data as any[]
      }
    })
  }
  function clearLoginCache() {
    bxAuthTicket.value = ''
    setUserInfo({})
    expireTime.value = 0
  }
  function logout() {
    bxAuthTicket.value = ''
    setUserInfo({})
    expireTime.value = 0
    navigateTo('/')
    ElMessage.success('退出成功')
  }

  async function scanAuth(code, state) {
    // 扫码登录 页面回调
    const data = await scanLogin(code, state)
    if (data?.state === 'SUCCESS') {
      const resp = data.response[0]
      if (resp.code === 'BIND') {
        // const { unionid, openid } = resp.response || {}
        // if (unionid && openid) {
        //   sessionStorage.setItem('BIND_UNIONID', unionid)
        //   sessionStorage.setItem('BIND_OPENID', openid)
        //   document.querySelectorAll('.right-box').forEach((item) => {
        //     if (item.className.includes('bind-right-box')) {
        //       item.style.display = 'block'
        //     }
        //     else {
        //       item.style.display = 'none'
        //     }
        //   })
        // }
      }
      else if (resp.code === 'CHOOSE') {
        // alert('扫码授权暂必须明确指定应用,请重新扫码登录')
        // var data = resp.response.data
        // reLogin(data[0].applicaiton)
      }
      else {
        const bx_auth_ticket = resp.response.bx_auth_ticket
        const current_login_user = resp.response.login_user_info
        bxAuthTicket.value = bx_auth_ticket
        setUserInfo(current_login_user)
        ElMessage.success('登录成功')
      }
    }
    else {
      ElMessage.error(data.resultMessage)
    }
  }
  return {
    loginVisible,
    setLoginVisible,
    setUserInfo,
    accountLogin,
    isLogin,
    userInfo,
    bxAuthTicket,
    logout,
    clearLoginCache,
    scanAuth,
    // pathBeforeLogin,
    // setPathBeforeLogin, // 设置登录前路径
    collectArticleMap, // 用户已收藏文章map
    getCollectArticleList, // 获取用户已收藏文章
    allowCloseLogin,
    setAllowCloseLogin,
  }
}, { persist: import.meta.client && true })

if (import.meta.hot)
  import.meta.hot.accept(acceptHMRUpdate(useUserStore, import.meta.hot))
